import { menu } from "../../decorator";
const { ccclass, property } = cc._decorator;

@ccclass
@menu(__filename)
export default class fadeAction extends cc.Component {
    @property
    private _begin = 0;
    @property
    get begin() { return this._begin; }
    set begin(v) { if (v >= 0 && v <= 255) this._begin = v; }

    @property
    private _end = 255;
    @property
    get end() { return this._end; }
    set end(v) { if (v >= 0 && v <= 255) this._end = v; }

    @property
    private _speed = 10;
    @property
    get speed() {
        if (this.begin == this.end) {
            return 0;
        } else if (this.begin > this.end) {
            return this._speed > 0 ? -this._speed : this._speed;;
        } else {
            return this._speed >= 0 ? this._speed : -this._speed;;
        }
    }
    set speed(v) { this._speed = v; }

    private stopAnimation = true;

    onEnable() {
        this.node.opacity = this.begin;
        this.stopAnimation = false;
    }

    update(dt: number) {
        if (this.stopAnimation) return;
        if (this.speed > 0) {
            this.node.opacity += this.speed * dt;
            if (this.node.opacity > this.end) {
                this.node.opacity = this.end;
            }
        } else if (this.speed < 0) {
            this.node.opacity += this.speed * dt;
            if (this.node.opacity < this.end) {
                this.node.opacity = this.end;
            }
        }
        if (this.node.opacity == this.end) {
            this.stopAnimation = true;
        }
    }
}
